package com.example.demo.utils;


import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.Charset;

public class HttpUtils {

    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);

    public static String doGet(String url) {
        String result = null;
        CloseableHttpClient httpclient = null;
        try {
            httpclient = HttpClients.createDefault();
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                result = EntityUtils.toString(response.getEntity(), "utf-8");
            } else {
                System.out.println("请求异常代码:::" + statusCode);
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        return result;
    }
    public static String getAccessToken() throws IOException {
        return doGet("http://one.wcwlvip.com/redis/get");
    }

    public static String doPostJson(String url, String json) throws IOException {
        String result = null;
        CloseableHttpClient httpclient = null;
        try {
            httpclient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();//设置请求和传输超时时间
            httpPost.setConfig(requestConfig);
            httpPost.setHeader("Accept", "application/json");
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setEntity(new StringEntity(json, Charset.forName("UTF-8")));
            HttpResponse response = httpclient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), "utf-8");
            }
            httpclient.close();
        } catch (IOException e) {
            logger.error(e.getMessage());
        } finally {
            if (httpclient != null) {
                httpclient.close();
            }
        }
        return result;
    }

    public static void main(String[] args) {
        System.out.println(doGet("http://127.0.0.1/rabbit/status?s=消费者1已完成"));
    }
}
